﻿using Chloe;
using Chloe.PostgreSQL;
using Chloe.SQLite;
using Chloe.SqlServer;
using Microsoft.Data.Sqlite;
using Npgsql;
using SQLitePCL;
using System;
using WebApiOrm.Provider;
using WebApiOrm.Provider.Chloe;

namespace Microsoft.Extensions.DependencyInjection
{
    /// <summary>
    /// OrmBuilder扩展
    /// 扩展添加具体的Orm
    /// </summary>
    public static class OrmBuilderExtensions
    {
        /// <summary>
        /// 添加Chloe
        /// </summary>
        /// <param name="builder"></param>
        /// <param name="connectionString"></param>
        /// <param name="ormName"></param>
        /// <returns></returns>
        public static IOrmBuilder AddChloe(this IOrmBuilder builder, string ormName)
        {
            builder.Services.AddOrmProvider<ChloeOrmProvider>(ormName);

            switch (builder.DatabaseType)
            {
                case DatabaseType.Sqlite:
                    SQLitePCL.raw.SetProvider(new SQLite3Provider_e_sqlite3());
                    builder.Services.AddScoped<IDbContext>(serviceProvider =>
                    {
                        return new SQLiteContext(() => new SqliteConnection(builder.ConnectionString));
                    });
                    break;

                case DatabaseType.SqlServer:
                    builder.Services.AddScoped<IDbContext>((serviceProvider) =>
                    {
                        return new MsSqlContext(builder.ConnectionString);
                    });
                    break;

                case DatabaseType.PostgreSQL:
                    builder.Services.AddScoped<IDbContext>(serviceProvider =>
                    {
                        return new PostgreSQLContext(() => new NpgsqlConnection(builder.ConnectionString))
                        {
                            ConvertToLowercase = false
                        };
                    });
                    break;

                default:
                    throw new NotSupportedException();
            }

            return builder;
        }

    }
}
